package com.lldpet.spring.cloud.demo.payment.service.listener;

import cn.ygyg.common.utils.JsonUtils;
import com.lldpet.spring.cloud.demo.order.client.channel.OrderSource;
import com.lldpet.spring.cloud.demo.order.client.event.OrderCreateSuccessEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;

import javax.annotation.Resource;

/**
 * @desc：OrderListener order 监听器
 * @author: guanliang.xue
 * @date: 2021/5/12 11:07
 * @version:
 * @since:
 */
@Configuration
@EnableBinding(OrderSource.class)
public class OrderListener {

    private static final Logger logger = LoggerFactory.getLogger(OrderListener.class);

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private BusProperties bus;


    @StreamListener(OrderSource.INPUT_CHANNEL)
    public void onOrderCreateSuccessEvent(RemoteApplicationEvent remoteApplicationEvent) {
        // 判断是否是 OrderCreateSuccessEvent 类型的事件
        if(remoteApplicationEvent instanceof OrderCreateSuccessEvent){
            logger.info("payment-service#OrderListener 监听到 订单创建成功事件");
            logger.info("OrderListener.orderCreateSuccessEvent: {}", JsonUtils.toText(remoteApplicationEvent));

            // ack
            OrderCreateSuccessEvent orderCreateSuccessEvent = (OrderCreateSuccessEvent)remoteApplicationEvent;
            orderCreateSuccessEvent.ack(bus,applicationEventPublisher,this);

            // 抛出异常，模拟消费失败
            //throw new RuntimeException("payment-service#OrderListener 消费消息失败");

        }
        // todo 监听到事件后到业务逻辑处理

    }

    @ServiceActivator(inputChannel = "orderExchange.paymentGroup.errors")
    public void error(Message<?> message){
        logger.info("orderExchange.paymentGroup.errors , 订单消息消费失败处理。 message: {}", message.toString());
    }
}
